package com.faner4cloud.yun.common.redis;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;

import java.util.concurrent.TimeUnit;

/**
 * @author ...zz
 * @version v1
 * @summary redis加锁
 * @since 2022/6/1 11:31 AM
 */
public class RedisLock {
	RedissonClient redissonClient;

	public RedisLock(RedissonClient redissonClient) {
		this.redissonClient = redissonClient;
	}

	/**
	 * 互斥锁，seconds秒后自动失效
	 * @param key
	 * @param seconds
	 */
	public boolean lock(String key, int seconds) {
		RLock rLock = redissonClient.getLock(key);
		if (rLock.isLocked()) {
			return false;
		}
		rLock.lock(seconds, TimeUnit.SECONDS);
		return true;
	}

	/**
	 * 互斥锁，自动续期
	 *
	 * @param key
	 */
	public boolean lock(String key) {
		RLock rLock = redissonClient.getLock(key);
		if (rLock.isLocked()) {
			return false;
		}
		rLock.lock();
		return true;
	}
	/**
	 * 上锁，后进入的休眠尝试再争夺
	 *
	 * @param key
	 */
	public boolean retryLock(String key) {
		while (true){
			RLock rLock = redissonClient.getLock(key);
			if (rLock.isLocked()) {
				try {
					Thread.sleep(500);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			} else {
				rLock.lock();
				break;
			}
		}
		return true;
	}
	/**
	 * 手动释放锁
	 *
	 * @param key
	 */
	public void unlock(String key) {
		RLock rLock = redissonClient.getLock(key);
//		if(rLock.isLocked()&&rLock.isHeldByCurrentThread()){
		if (rLock.isLocked()) {
			rLock.unlock();
		}
	}

	/**
	 * 尝试获取锁
	 * @param key
	 * @param timeout
	 * @return
	 * @throws InterruptedException
	 */
	public boolean tryLock(String key, Long timeout) throws InterruptedException {
		RLock rLock = redissonClient.getLock(key);
		return rLock.tryLock(timeout, TimeUnit.SECONDS);
	}

	/**
	 * 这里简单的增加了等待时间来获取锁
	 *
	 * @param key
	 * @throws InterruptedException
	 */
	public void blockedLock(String key) throws InterruptedException {
		this.tryLock(key,120L);
	}
}
